#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
记录服务
"""

import logging
from datetime import datetime
from bson import ObjectId
from db.mongo import get_db
from base.models.record import RecordServiceModel, RequestRecordModel

logger = logging.getLogger(__name__)

class RecordService:
    """记录服务"""

    @staticmethod
    def create_record_service(service_name, service_ip=None, service_port=None):
        """
        创建记录服务

        Args:
            service_name: 服务名称
            service_ip: 服务IP地址
            service_port: 服务端口

        Returns:
            str: 服务ID
        """
        db = get_db()

        # 检查服务名称是否已存在
        existing_service = db.record_services.find_one({"service_name": service_name})
        if existing_service:
            return existing_service["_id"]

        # 创建记录服务
        service = RecordServiceModel(
            service_name=service_name,
            service_ip=service_ip,
            service_port=service_port
        )
        service_dict = service.to_dict()

        # 插入记录服务
        db.record_services.insert_one(service_dict)
        service_id = service_dict["_id"]

        return service_id

    @staticmethod
    def get_record_services(page=1, page_size=10):
        """
        获取记录服务列表

        Args:
            page: 页码
            page_size: 每页大小

        Returns:
            dict: 包含记录服务列表和总数的字典
        """
        db = get_db()

        # 计算跳过的记录数
        skip = (page - 1) * page_size

        # 查询记录服务
        services = list(db.record_services.find().sort("created_at", -1).skip(skip).limit(page_size))

        # 获取总记录数
        total = db.record_services.count_documents({})

        return {
            "services": services,
            "total": total,
            "page": page,
            "page_size": page_size,
            "pages": (total + page_size - 1) // page_size
        }

    @staticmethod
    def get_record_service_by_id(service_id):
        """
        根据ID获取记录服务

        Args:
            service_id: 服务ID

        Returns:
            dict: 记录服务详情
        """
        db = get_db()

        # 查询记录服务
        service = db.record_services.find_one({"_id": service_id})
        if not service:
            return None

        return service

    @staticmethod
    def update_record_service(service_id, service_name=None, service_ip=None, service_port=None, is_active=None):
        """
        更新记录服务

        Args:
            service_id: 服务ID
            service_name: 服务名称
            service_ip: 服务IP地址
            service_port: 服务端口
            is_active: 是否激活

        Returns:
            bool: 是否成功更新
        """
        db = get_db()

        # 查询记录服务
        service = db.record_services.find_one({"_id": service_id})
        if not service:
            return False

        # 准备更新数据
        update_data = {"updated_at": datetime.utcnow()}
        if service_name is not None:
            update_data["service_name"] = service_name
        if service_ip is not None:
            update_data["service_ip"] = service_ip
        if service_port is not None:
            update_data["service_port"] = service_port
        if is_active is not None:
            update_data["is_active"] = is_active

        # 更新记录服务
        db.record_services.update_one({"_id": service_id}, {"$set": update_data})

        return True

    @staticmethod
    def delete_record_service(service_id):
        """
        删除记录服务

        Args:
            service_id: 服务ID

        Returns:
            bool: 是否成功删除
        """
        db = get_db()

        # 查询记录服务
        service = db.record_services.find_one({"_id": service_id})
        if not service:
            return False

        # 删除相关的请求记录
        db.request_records.delete_many({"service_id": service_id})

        # 删除记录服务
        db.record_services.delete_one({"_id": service_id})

        return True

    @staticmethod
    def create_request_record(service_id, client_service_name, server_service_name, request_method, request_url,
                             request_headers, request_body, response_status, response_headers, response_body,
                             request_timestamp=None, response_timestamp=None, duration_ms=None):
        """
        创建请求记录

        Args:
            service_id: 服务ID
            client_service_name: 客户端服务名称
            server_service_name: 服务端服务名称
            request_method: 请求方法
            request_url: 请求URL
            request_headers: 请求头
            request_body: 请求体
            response_status: 响应状态码
            response_headers: 响应头
            response_body: 响应体
            request_timestamp: 请求时间戳
            response_timestamp: 响应时间戳
            duration_ms: 请求持续时间（毫秒）

        Returns:
            str: 请求记录ID
        """
        db = get_db()

        # 创建请求记录
        record = RequestRecordModel(
            service_id=service_id,
            client_service_name=client_service_name,
            server_service_name=server_service_name,
            request_method=request_method,
            request_url=request_url,
            request_headers=request_headers,
            request_body=request_body,
            response_status=response_status,
            response_headers=response_headers,
            response_body=response_body
        )

        if request_timestamp:
            record.request_timestamp = request_timestamp
        if response_timestamp:
            record.response_timestamp = response_timestamp
        if duration_ms:
            record.duration_ms = duration_ms
        else:
            # 计算请求持续时间
            delta = record.response_timestamp - record.request_timestamp
            record.duration_ms = int(delta.total_seconds() * 1000)

        record_dict = record.to_dict()

        # 插入请求记录
        db.request_records.insert_one(record_dict)
        record_id = record_dict["_id"]

        return record_id

    @staticmethod
    def get_request_records(service_id=None, page=1, page_size=10):
        """
        获取请求记录列表

        Args:
            service_id: 服务ID（可选）
            page: 页码
            page_size: 每页大小

        Returns:
            dict: 包含请求记录列表和总数的字典
        """
        db = get_db()

        # 构建查询条件
        query = {}
        if service_id:
            query["service_id"] = service_id

        # 计算跳过的记录数
        skip = (page - 1) * page_size

        # 查询请求记录
        records = list(db.request_records.find(query).sort("created_at", -1).skip(skip).limit(page_size))

        # 获取总记录数
        total = db.request_records.count_documents(query)

        return {
            "records": records,
            "total": total,
            "page": page,
            "page_size": page_size,
            "pages": (total + page_size - 1) // page_size
        }

    @staticmethod
    def get_request_record_by_id(record_id):
        """
        根据ID获取请求记录

        Args:
            record_id: 请求记录ID

        Returns:
            dict: 请求记录详情
        """
        db = get_db()

        # 查询请求记录
        record = db.request_records.find_one({"_id": record_id})
        if not record:
            return None

        return record

    @staticmethod
    def delete_request_record(record_id):
        """
        删除请求记录

        Args:
            record_id: 请求记录ID

        Returns:
            bool: 是否成功删除
        """
        db = get_db()

        # 查询请求记录
        record = db.request_records.find_one({"_id": record_id})
        if not record:
            return False

        # 删除请求记录
        db.request_records.delete_one({"_id": record_id})

        return True

    @staticmethod
    def convert_to_request_definition(record_id):
        """
        将请求记录转换为请求定义

        Args:
            record_id: 请求记录ID

        Returns:
            dict: 请求定义
        """
        db = get_db()

        # 查询请求记录
        record_dict = db.request_records.find_one({"_id": record_id})
        if not record_dict:
            return None

        # 转换为请求记录对象
        record = RequestRecordModel.from_dict(record_dict)

        # 转换为请求定义
        request_definition = record.to_request_definition()

        return request_definition
